//
//  GRLoginViewController.m
//  YC_GRice
//
//  Created by LiuFeng on 2018/7/9.
//  Copyright © 2018年 YeCai. All rights reserved.
//

#import "GRLoginViewController.h"
#import "GRRegisterViewController.h"
#import "GRNoInteractionViewController.h"

#import "UIButton+Common.h"
#import "GRPointSideButton.h"
#import "LFTextField.h"
#import <CloudPushSDK/CloudPushSDK.h>

@interface GRLoginViewController () <LFTextFieldDelegate>

{
    BOOL isPasswordLoginMode; // 是否密码登录（默认验证码登录）
}
// Layout
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *mobileTopLayout; // 手机号top layout
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *mobileBottomLayout;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *secretTopLayout;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *secretBottomLayout;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *otherWayTopLayout;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topLayout;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *imgAspect;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *authcodeWidthLayout;

@property (weak, nonatomic) IBOutlet UIImageView *LogIMG;
@property (weak, nonatomic) IBOutlet LFTextField *mobileTF;
@property (weak, nonatomic) IBOutlet LFTextField *authcodeTF;
@property (weak, nonatomic) IBOutlet GRPointSideButton *forgetPasswordBtn;

@property (weak, nonatomic) IBOutlet UIButton *loginBtn;
@property (weak, nonatomic) IBOutlet UILabel *loginMode;

@property (nonatomic, strong) UMSocialUserInfoResponse *response;

@end

@implementation GRLoginViewController

- (IBAction)getBack:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self adjustLayout];
}


/**
 布局调整
 */
- (void)adjustLayout {
    if (KscreenWidth == 320) {
        _mobileTopLayout.constant      = 25;
        _mobileBottomLayout.constant = 5;
        _secretTopLayout.constant     = 5;
        _secretBottomLayout.constant = 5;
        _otherWayTopLayout.constant  = 20;
    }
    
    if (IS_IPHONEX) {
        _LogIMG.image           = [UIImage imageNamed:@"login_X"];
        _imgAspect.constant   = 375.0/274;
        _topLayout.constant   = 50;
    }
    
    self.mobileTF.text           = [GRUserBasisInfo UserBasis].mobile;
    self.mobileTF.limitNum      = 11;
    self.authcodeTF.delegate  = self;
    [self switchLoginMode];
}


/**
 实时改变登录按钮颜色以及交互

 @param textField <#textField description#>
 @param text <#text description#>
 */
-(void)textField:(UITextField *)textField textDidChange:(NSString *)text {
    [self changeLoginBtnStatus:(text.length > 0 ? YES : NO)];
}

- (void)changeLoginBtnStatus:(BOOL)status {
    if (self.loginBtn.enabled != status) {
        self.loginBtn.enabled         = status;
        self.loginBtn.selected        = status;
        self.loginBtn.backgroundColor = status ? KGMTHEM_COLOR : KGMBACKGROUND_COLOR;
    }
}

/**
 切换登录方式
 */
- (void)switchLoginMode {
    self.authcodeTF.text = @"";
    if (isPasswordLoginMode) {
        self.loginMode.text               = @"验证码登录";
        self.authcodeTF.limitNum          = 16;
        self.authcodeTF.placeholder       = @"输入密码";
        self.authcodeTF.keyboardType      = UIKeyboardTypeDefault;
        self.authcodeTF.secureTextEntry   = YES;
        self.forgetPasswordBtn.hidden     = NO;
        self.authcodeWidthLayout.constant = 0;
    }else {
        self.loginMode.text               = @"密码登录";
        self.authcodeTF.limitNum          = 6;
        self.authcodeTF.placeholder       = @"输入验证码";
        self.authcodeTF.keyboardType      = UIKeyboardTypeNumberPad;
        self.authcodeTF.secureTextEntry   = NO;
        self.forgetPasswordBtn.hidden     = YES;
        self.authcodeWidthLayout.constant = 85;
    }
}

/**
 龟米用户协议

 @param sender <#sender description#>
 */
- (IBAction)userAgreement:(id)sender {
    GRNoInteractionViewController *web = [[GRNoInteractionViewController alloc] init];
    web.URL = @"https://new.xiaoguikuaipao.com/protocol.html";
    web.titleAutomation = YES;
    [self.navigationController pushViewController:web animated:YES];
}


/**
 获取验证码

 @param sender <#sender description#>
 */
- (IBAction)getAuthCode:(UIButton *)sender {
    
    NSDictionary* dictionary = @{@"paramer": @{@"mobile":self.mobileTF.text,
                                               @"type"  :@"login",
                                               @"app"   :@"gm"
                                              },
                                 @"sender" : sender
                                 };
    [GRLoginAction getVerificationCode:dictionary];
}


/**
 登录

 @param sender <#sender description#>
 */
- (IBAction)loginAction:(UIButton *)sender {
    [self gotoLoginWithType:(isPasswordLoginMode ? @"password" : @"captcha") sender:sender];
}


/**
 微信登录 或 验证码登录 或 密码登录

 @param type <#type description#>
 */
- (void)gotoLoginWithType:(NSString *)type sender:(UIButton *)sender{
    sender.enabled   = NO;
    NSString *adcode = [GRLocationManager defaultManager].currentpoi.adcode ? [GRLocationManager defaultManager].currentpoi.adcode : @"";
    NSMutableDictionary *paramer = [@{@"areaCode"     : adcode,
                                      @"mobile"       : self.mobileTF.text,
                                      @"code"         : self.authcodeTF.text,
                                      @"password"   : self.authcodeTF.text,
                                      @"type"          : type,
                                      @"source"       : @"ios",
                                      @"deviceId"     : [CloudPushSDK getDeviceId],
                                      @"version"      : [UIDevice currentDevice].systemVersion,
                                      @"sourceWechat" : @"app"
                                    } mutableCopy];
    if (self.response) {
        [paramer addEntriesFromDictionary:@{@"avatar"  : self.response.iconurl,
                                            @"name"    : self.response.name,
                                            @"sex"     : [self.response.gender isEqualToString:@"f"] ? @"female" : @"male",
                                            @"openId"  : self.response.openid,
                                            @"unionId" : self.response.unionId,
                                            }];
    }
WEAKSELF
    [GRLoginAction gotoLoginWithParamer:paramer completionHandler:^(BOOL success, id responseObject, GRError *error) {
        if (success) {
            GRBasisKeyModel *model = [GRBasisKeyModel yy_modelWithDictionary:responseObject];
            if (model) {
                [[GRUserBasisInfo shareBasis] saveBasisKey:model];
                [[GRUserBasisInfo shareBasis] doLogin];
            }
            [weakSelf getBack:nil];
        }else {
            if ([error.errorCode integerValue] == 1000) {
                [weakSelf gotoRegisterWithMode:GRRegisterModeAssociatedMobile];
            }else {
                [GRHUD showMessage:error.errorMsg atView:weakSelf.view];
            }
        }
        sender.enabled = YES;
    }];
}

/**
 注册

 @param sender <#sender description#>
 */
- (IBAction)registerAction:(id)sender {
    [self gotoRegisterWithMode:GRRegisterModeNewAccount];
}


/**
 忘记密码

 @param sender <#sender description#>
 */
- (IBAction)forgetPasswordAction:(id)sender {
    [self gotoRegisterWithMode:GRRegisterModeForgetLoginPassword];
}

- (void)gotoRegisterWithMode:(RegisterMode)mode {
    GRRegisterViewController *registerVc = [[GRRegisterViewController alloc] init];
    registerVc.registerMode = mode;
    if (mode == GRRegisterModeNewAccount || mode == GRRegisterModeSetLoginPassword) {
        registerVc.isTop    = YES;
    }
    registerVc.UMResponse   = self.response;
    [self.navigationController pushViewController:registerVc animated:YES];
}

/**
 微信登录

 @param sender <#sender description#>
 */
- (IBAction)wechtLogin:(UIButton *)sender {
    [[UMSocialManager defaultManager] getUserInfoWithPlatform:UMSocialPlatformType_WechatSession currentViewController:self completion:^(id result, NSError *error) {
        if (!error) {
            self.response = result;
            [self gotoLoginWithType:@"wechat" sender:sender];
        }
    }];
}


/**
 密码或验证码登录-切换

 @param sender <#sender description#>
 */
- (IBAction)passwordLogin:(UIButton *)sender {
    sender.selected = !sender.selected;
    isPasswordLoginMode = sender.selected;
    [self switchLoginMode];
}



/**
 内存警告
 */
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
